package com.jia.sms.interceptor;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.jia.constant.RedisConstant;
import com.jia.sms.constants.SmsRedisConstant;
import com.jia.sms.entity.User;
import com.jia.sms.holder.UserHolder;
import org.jetbrains.annotations.NotNull;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author jia
 */
public class RefreshTokenInterceptor implements HandlerInterceptor {

    private final StringRedisTemplate stringRedisTemplate;

    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public static String REDIS_TOKEN_PREFIX = RedisConstant.PROJECT_REDIS_PREFIX
            + SmsRedisConstant.BUSINESS_SMS_PREFIX
            + SmsRedisConstant.TOKEN_PREFIX;

    @Override
    public boolean preHandle(@NotNull HttpServletRequest request,
                             @NotNull HttpServletResponse response,
                             @NotNull Object handler) throws Exception {
        // 1. 从请求中获取到token
        String token = request.getHeader("authorization");
        if (StringUtils.isEmpty(token)) {
            return true;
        }
        String key = REDIS_TOKEN_PREFIX + token;
        // 2. 依据Token 获取到用户信息
        Map<Object, Object> entries = stringRedisTemplate.opsForHash().entries(key);
        if (entries.isEmpty()) {
            // 3. 不存在，拦截
            response.setStatus(401);
            return false;
        }

        // 4. 将获取的用户信息Hash 转成 实例
        User user = BeanUtil.fillBeanWithMap(entries, new User(), false);

        // 5. 保存用户信息到ThreadLocal
        UserHolder.saveUser((User) user);

        // 6. 刷新Token 有效期
        stringRedisTemplate.expire(key, 30, TimeUnit.MINUTES);

        // 7. 放行
        return true;
    }

    @Override
    public void afterCompletion(@NotNull HttpServletRequest request,
                                @NotNull HttpServletResponse response,
                                @NotNull Object handler, Exception ex) throws Exception {
        UserHolder.removeUser();
    }
}
